package com.wsx.ones.monitor.core.executer;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程工程的实现类，个性化线程创建名称
 * Created by wangshuaixin on 17/2/6.
 */
public class RpcThreadFactory implements ThreadFactory {

    //定义线程自增的线程名字
    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    private String threadName;

    /**
     * 初始化线程池功能生成线程时的变量
     * @param threadName
     */
    public RpcThreadFactory(String threadName) {
        this.threadName = threadName;
        SecurityManager s = System.getSecurityManager();
        group = (null != s) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        namePrefix = "rpcPool-" + poolNumber.getAndIncrement() + "-thread-";
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement() + threadName, 0);
        if (t.isDaemon()) {
            t.setDaemon(false);
        }
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }
}
